package demo1.service;

import demo1.dao.Mapper.goodsMapper;
import demo1.dao.Mapper.userBuyMapper;
import demo1.dao.sql.goodssql;
import demo1.dao.sql.userBuysql;
import demo1.pojo.*;

import java.sql.ResultSet;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class userBuyService {
    public void addAddress(String usersAddress,int gouwuid)throws Exception{//添加地址
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.addAddress(usersAddress,gouwuid);
    }
    public void addMoney(int newmoney,int gouwuid)throws Exception{//充值到用户
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.updateMoney(newmoney,gouwuid);
    }
    public void addToGouwucar(int goodsID,int gouwuid)throws Exception{//添加到购物车里面
        userBuyMapper userBuyMapper = new userBuysql();
        goodsMapper goodsMapper = new goodssql();
        goods good = new goods();
        good = goodsMapper.selectByGoodsId(goodsID);//通过获取id来获取对应商品的信息
        String goodsName = good.getGoodsName();
        String goodsMessage = good.getGoodsMessage();
        int price = good.getPrice();
        //查看避免重复添加到购物车
        if(userBuyMapper.checkGouwucar(gouwuid, goodsName,goodsMessage) == 1){
            //如果没有该商品
            userBuyMapper.insertGoods(gouwuid, price,goodsMessage,goodsName,0);
        }
    }
    public int checkOrderForm(int gouwuid)throws Exception{//检查有没有存在订单
        userBuyMapper userBuyMapper = new userBuysql();
        ResultSet rs;
        rs = userBuyMapper.selectAllBygouwuid(gouwuid);
        while (rs.next()){
            if(gouwuid == rs.getInt("gouwuid")){
                //如果存在订单
                //resp.sendRedirect("failOrderForm.jsp");
                return 1;
            }
        }
        return 0;
    }
    public orderform createOrderForm(int gouwuid)throws Exception{//生成购物车中所有商品的订单
        userBuyMapper userBuyMapper = new userBuysql();
        List<gouwucar> gouwucarList = new ArrayList<>();
        int sum = 0;
        gouwucarList = userBuyMapper.selectAll(gouwuid);
        for (gouwucar gouwucar : gouwucarList){
            sum += gouwucar.getPrice();//总结钱的数目
        }
        LocalDateTime currentTime = LocalDateTime.now();

        // 在当前时间基础上增加5分钟
        LocalDateTime futureTime = currentTime.plusMinutes(5);

        // 格式化为指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedFutureTime = futureTime.format(formatter);

        userBuyMapper.insertOrderForm(sum, Timestamp.valueOf(formattedFutureTime), gouwuid, -1);
        orderform orderform = new orderform();
        orderform.setTime(Timestamp.valueOf(formattedFutureTime));//把订单结束时间写入数据库
        orderform.setMoney(sum);
        orderform.setGoodsGroup(-1);//-1就表示结算的是所有商品，而不是部分商品
        return orderform;
    }
    public orderform createOrderFormByGroup(int gouwuid,int id)throws Exception{//生成购物车中部分商品的订单
        userBuyMapper userBuyMapper = new userBuysql();
        //如果没有订单,就可以生成
        List<gouwucar> gouwucarList = new ArrayList<>();
        int sum = 0;
        int goodsGroup = userBuyMapper.selectgoodsGroup(id);
        gouwucarList = userBuyMapper.selectAllByGoodsGroup(goodsGroup,gouwuid);
        for (gouwucar gouwucar : gouwucarList){
            sum += gouwucar.getPrice();
        }
        LocalDateTime currentTime = LocalDateTime.now();
        // 在当前时间基础上增加5分钟
        LocalDateTime futureTime = currentTime.plusMinutes(5);

        // 格式化为指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedFutureTime = futureTime.format(formatter);

        userBuyMapper.insertOrderForm(sum, Timestamp.valueOf(formattedFutureTime), gouwuid, goodsGroup);
        orderform orderform = new orderform();
        orderform.setTime(Timestamp.valueOf(formattedFutureTime));
        orderform.setMoney(sum);
        orderform.setGoodsGroup(goodsGroup);
        return orderform;
    }
    public void deleteAddress(int addressID)throws Exception{//删除地址
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.deleteAddress(addressID);
    }
    public void deleteAll(int gouwuid)throws Exception{//清空购物车
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.deleteAll(gouwuid);
    }
    public void deleteGouwucarGoods(int id)throws Exception{//删除某种商品
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.deleteGoods(id);
    }
    public void deleteOrderForm(int gouwuid)throws Exception{//取消并删除订单
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.deleteOrderForm(gouwuid);
    }
    public List<gouwucar> managementGouwucar(int gouwuid)throws Exception{//管理自己的购物车
        List<gouwucar> gouwucarList;
        userBuyMapper userBuyMapper = new userBuysql();
        gouwucarList = userBuyMapper.selectAll(gouwuid);//再次查询
        return gouwucarList;
    }
    public void checkGoodsStatue(int gouwuid)throws Exception{//检查商品状态，如果处于下架状态就删除商品
        List<gouwucar> gouwucarList;
        userBuyMapper userBuyMapper = new userBuysql();
        gouwucarList = userBuyMapper.selectAll(gouwuid);
        for (gouwucar gouwucar : gouwucarList){
            String goodsName = gouwucar.getGoodsName();
            String goodsMessage = gouwucar.getGoodsMessage();
            int num = -1;
            goodsMapper goodsMapper = new goodssql();
            num = goodsMapper.selectByGoodsstatueByName(goodsName,goodsMessage);
            if(num == 0){//处于下架状态
                userBuyMapper.deleteGoodsByName(gouwuid, goodsName,goodsMessage);//删除商品
            }
        }
    }
    public address modifyAddress(int addressID)throws Exception{//修改某个地址
        userBuyMapper userBuyMapper = new userBuysql();
        address address = userBuyMapper.select(addressID);
        return address;
    }
    public void payOrderForm()throws Exception{//支付订单
        //检查时间有没有过，检查钱够不够，钱要减少，销量增加，库存减少，如果库存为0，设置为下架
        userBuyMapper userBuyMapper = new userBuysql();
    }
    public int checkTime(int gouwuid)throws Exception{//检查时间有没有过
        userBuyMapper userBuyMapper = new userBuysql();
        LocalDateTime currentTime = LocalDateTime.now();
        // 格式化为指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedFutureTime = currentTime.format(formatter);
        Timestamp timestamp1 = Timestamp.valueOf(formattedFutureTime);

        ResultSet rs = userBuyMapper.selectAllBygouwuid(gouwuid);
        if (rs.next()) {//先检查时间有没有过
            if (timestamp1.compareTo(rs.getTimestamp("time")) < 0) {
                //时间还没有到
                return 1;
            }else {
                return 0;
            }
        }
        else {//如果没有订单
            return -1;
        }

    }
    public int checkMoney(int gouwuid,int getMoney)throws Exception{//检查钱够不够
        userBuyMapper userBuyMapper = new userBuysql();
        ResultSet rs = userBuyMapper.selectAllBygouwuid(gouwuid);
        int money = 0;
        if(rs.next()){
            money = rs.getInt("money");
        }

        if(money > getMoney) {
            //钱不够
            return 0;
        }
        else {
            return 1;
        }
    }
    public void decrease(int gouwuid)throws Exception{//减少库存，增加销量
        userBuyMapper userBuyMapper = new userBuysql();
        ResultSet rs = userBuyMapper.selectAllBygouwuid(gouwuid);
        int goodsGroup = -2;
        if(rs.next()){
            goodsGroup = rs.getInt("goodsGroup");
        }
        if(goodsGroup == -1){//如果是所有商品
            List<gouwucar> gouwucarList = new ArrayList<>();
            gouwucarList = userBuyMapper.selectAll(gouwuid);
            goodsMapper goodsMapper = new goodssql();
            int goodsNum = 0;//获取库存
            int goodsXiaoLiang = 0;
            for (gouwucar gouwucar : gouwucarList){

                String goodsName = gouwucar.getGoodsName();
                String goodsMessage = gouwucar.getGoodsMessage();
                goodsNum = goodsMapper.selectByGoodsByName(goodsName,goodsMessage);//获取当前库存
                goodsMapper.updateGoodsNumByName((goodsNum-1),goodsName,goodsMessage);//更新库存
                if(goodsNum == 1){
                    goodsMapper.updateGoodsStatueByName("下架",goodsName,goodsMessage);//商品下架
                    //userBuyMapper.deleteGoodsByName(gouwuid,goodsName,goodsMessage);//删除购物车中下架的商品
                }
                goodsXiaoLiang = goodsMapper.selectByGoodsXiaoLiangByName(goodsName,goodsMessage);//获取当前销量
                goodsMapper.updateGoodsXiaoLiangByName((goodsXiaoLiang+1),goodsName,goodsMessage);//更新销量
                //userBuyMapper.deleteOrderForm(gouwuid);//支付后删除订单
            }
        }
        else {
            List<gouwucar> gouwucarList = new ArrayList<>();
            gouwucarList = userBuyMapper.selectAllByGoodsGroup(goodsGroup, gouwuid);
            goodsMapper goodsMapper = new goodssql();
            int goodsNum = 0;//获取库存
            int goodsXiaoLiang = 0;
            for (gouwucar gouwucar : gouwucarList){

                String goodsName = gouwucar.getGoodsName();
                String goodsMessage = gouwucar.getGoodsMessage();
                goodsNum = goodsMapper.selectByGoodsByName(goodsName,goodsMessage);//获取当前库存
                goodsMapper.updateGoodsNumByName((goodsNum-1),goodsName,goodsMessage);//更新库存
                //如果库存为0，取消上架状态
                if(goodsNum == 1){
                    String statue = "下架";
                    goodsMapper.updateGoodsStatueByName(statue,goodsName,goodsMessage);
                    //userBuyMapper.deleteGoodsByName(gouwuid,goodsName,goodsMessage);//删除购物车中下架的商品
                }
                goodsXiaoLiang = goodsMapper.selectByGoodsXiaoLiangByName(goodsName,goodsMessage);//获取当前销量
                goodsMapper.updateGoodsXiaoLiangByName((goodsXiaoLiang+1),goodsName,goodsMessage);//更新销量
                //userBuyMapper.deleteOrderForm(gouwuid);//支付后删除订单
            }
        }
    }
    public void increase(int gouwuid)throws Exception{//如果支付失败，商品回退到原来的状态，增加库存，减少销量
        userBuyMapper userBuyMapper = new userBuysql();
        ResultSet rs = userBuyMapper.selectAllBygouwuid(gouwuid);
        int goodsGroup = -2;
        if(rs.next()){
            goodsGroup = rs.getInt("goodsGroup");
        }
        if(goodsGroup == -1){//如果是所有商品
            List<gouwucar> gouwucarList = new ArrayList<>();
            gouwucarList = userBuyMapper.selectAll(gouwuid);
            goodsMapper goodsMapper = new goodssql();
            int goodsNum = 0;//获取库存
            int goodsXiaoLiang = 0;
            for (gouwucar gouwucar : gouwucarList){

                String goodsName = gouwucar.getGoodsName();
                String goodsMessage = gouwucar.getGoodsMessage();
                goodsNum = goodsMapper.selectByGoodsByName(goodsName,goodsMessage);//获取当前库存
                goodsMapper.updateGoodsNumByName((goodsNum+1),goodsName,goodsMessage);//更新库存
                if(goodsNum == 0){
                    goodsMapper.updateGoodsStatueByName("上架",goodsName,goodsMessage);//商品上架
                }
                goodsXiaoLiang = goodsMapper.selectByGoodsXiaoLiangByName(goodsName,goodsMessage);//获取当前销量
                goodsMapper.updateGoodsXiaoLiangByName((goodsXiaoLiang-1),goodsName,goodsMessage);//更新销量
                //userBuyMapper.deleteOrderForm(gouwuid);//支付后删除订单
            }
        }
        else {
            List<gouwucar> gouwucarList = new ArrayList<>();
            gouwucarList = userBuyMapper.selectAllByGoodsGroup(goodsGroup, gouwuid);
            goodsMapper goodsMapper = new goodssql();
            int goodsNum = 0;//获取库存
            int goodsXiaoLiang = 0;
            for (gouwucar gouwucar : gouwucarList){

                String goodsName = gouwucar.getGoodsName();
                String goodsMessage = gouwucar.getGoodsMessage();
                goodsNum = goodsMapper.selectByGoodsByName(goodsName,goodsMessage);//获取当前库存
                goodsMapper.updateGoodsNumByName((goodsNum+1),goodsName,goodsMessage);//更新库存
                if(goodsNum == 0){
                    String statue = "上架";
                    goodsMapper.updateGoodsStatueByName(statue,goodsName,goodsMessage);
                }
                goodsXiaoLiang = goodsMapper.selectByGoodsXiaoLiangByName(goodsName,goodsMessage);//获取当前销量
                goodsMapper.updateGoodsXiaoLiangByName((goodsXiaoLiang-1),goodsName,goodsMessage);//更新销量
                //userBuyMapper.deleteOrderForm(gouwuid);//支付后删除订单
            }
        }
    }
    public int updateMoney(int gouwuid,int getMoney)throws Exception {
        userBuyMapper userBuyMapper = new userBuysql();
        ResultSet rs = userBuyMapper.selectAllBygouwuid(gouwuid);
        int money = 0;
        if (rs.next()) {
            money = rs.getInt("money");
        }
        int newmoney = getMoney - money;//减去后的金额
        userBuyMapper.updateMoney(newmoney, gouwuid);//设置新的金额
        return newmoney;
    }
    public List<address> searchAddress(String usersAddress,int gouwuid)throws Exception{//模糊查询地址
        List<address> addressList;
        userBuyMapper userBuyMapper = new userBuysql();
        addressList = userBuyMapper.searchAddress(usersAddress,gouwuid);//查询用户对应地址
        return addressList;
    }
    public List<goods> searchGoods(String goodsName)throws Exception{//模糊查询商品
        List<goods> goodsList;
        goodsMapper goodsMapper = new goodssql();
        goodsList = goodsMapper.selectPart(goodsName);
        return goodsList;
    }
    public String  setLocalAddress(int addressID,int gouwuid)throws Exception{//设置把选中的地址作为为默认地址
        userBuyMapper userBuyMapper = new userBuysql();
        address address = userBuyMapper.select(addressID);
        userBuyMapper.updateUserAddress(address.getUsersAddress(),gouwuid);
        return address.getUsersAddress();
    }
    public List<address> showAddress(int gouwuid)throws Exception{//展示所有地址
        List<address> addressList;
        userBuyMapper userBuyMapper = new userBuysql();
        addressList = userBuyMapper.selectById(gouwuid);//查询用户对应地址
        return addressList;
    }
    public List<goods> showAllGoods()throws Exception{//展示所有已经上架的商品信息，按上架时间的早晚排序
        List<goods> goodsList;
        goodsMapper goodsMapper = new goodssql();//调用接口
        goodsList = goodsMapper.selectAllEarly();//查询用户对应的商品
        return goodsList;
    }
    public List<goods> showAllGoodsLate()throws Exception {//展示所有已经上架的商品信息，按上架时间的早晚排序
        List<goods> goodsList;
        goodsMapper goodsMapper = new goodssql();//调用接口
        goodsList = goodsMapper.selectAllLate();//查询用户对应的商品
        return goodsList;
    }
    public List<goods> showAllGoodsXiaoLiang()throws Exception{//展示所有已经上架的商品信息，按销量的多少排序
        List<goods> goodsList;
        goodsMapper goodsMapper = new goodssql();//调用接口
        goodsList = goodsMapper.selectAllXiaoLiangHigh();//查询商品销量升序排序
        return goodsList;
    }
    public List<goods> showAllGoodsXiaoLiangLower()throws Exception{//展示所有已经上架的商品信息，按销量的多少排序
        List<goods> goodsList;
        goodsMapper goodsMapper = new goodssql();//调用接口
        goodsList = goodsMapper.selectAllXiaoLiangLower();//查询商品销量升序排序
        return goodsList;
    }
    public gouwucar showGoodsGroup(int id)throws Exception{//展示购物车中商品的分组情况，后期是按照分组来结算订单的
        userBuyMapper userBuyMapper = new userBuysql();
        gouwucar gouwucar = new gouwucar();
        gouwucar = userBuyMapper.selectByGouwuid(id);
        return gouwucar;
    }
    public orderform showOrderForm(int gouwuid)throws Exception{//展示订单的信息
        userBuyMapper userBuyMapper = new userBuysql();
        orderform orderform = new orderform();
        ResultSet rs = userBuyMapper.selectAllBygouwuid(gouwuid);
        if(rs.next()){
            orderform.setGoodsGroup(rs.getInt("goodsGroup"));
            orderform.setTime(rs.getTimestamp("time"));
            orderform.setMoney(rs.getInt("money"));
            return orderform;
        }
        return orderform;
    }
    public void updateAddress(String usersAddress,int addressID)throws Exception{//修改地址
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.updateAddress(usersAddress,addressID);
    }
    public void updateGroup(int goodsGroup,int id)throws Exception{//修改购物车中商品分组
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.updateGroup(goodsGroup,id);
    }
    public int checkLogin(String userName,String userPwd)throws Exception{//检查有没有该用户
        userBuyMapper userBuyMapper = new userBuysql();
        ResultSet rs = null;
        rs = userBuyMapper.selectAll(userName,userPwd);//查询所有
        if(rs.next()){//用户存在
            return 1;
        }
        else {//用户不存在
            return 0;
        }
    }
    public userBuy writeUser(String userName,String userPwd)throws Exception{//写入user对象
        userBuyMapper userBuyMapper = new userBuysql();
        ResultSet rs = null;
        rs = userBuyMapper.selectAll(userName,userPwd);//查询所有
        if(rs.next()){
            userBuy users = new userBuy();//写入用户
            users.setUserName(userName);
            users.setUserPwd(userPwd);
            users.setGouwuid(rs.getInt("gouwuid"));
            users.setUserAddress(rs.getString("userAddress"));
            users.setMoney(rs.getInt("money"));
            return users;
        }
        return null;
    }
    public void userBuyModifypop(String userName,int gouwuid)throws Exception{//修改用户的个人信息
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.updateUserBuyName(userName, gouwuid);
    }
    public void userBuyModifyPwd(String userPwd,int gouwuid)throws Exception{//修改用户的密码
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.updateUserBuyPwd(userPwd,gouwuid);//设置新密码
    }
    public void userBuyRegister(String userName,String userPwd)throws Exception{//实现注册
        userBuyMapper userBuyMapper = new userBuysql();
        userBuyMapper.insertUserBuy(userName,userPwd);
    }
    public int checkUserName(String userName)throws Exception{//检查有没有用户名
        userBuyMapper userBuyMapper = new userBuysql();
        ResultSet rs = userBuyMapper.select();
        while (rs.next()){
            if(Objects.equals(userName, rs.getString("userName"))){
                //如果有一样的用户名了
                return 0;
            }
        }
        return 1;
    }
}
